<?php
namespace app\model\frontend;

use think\Model;

use think\facade\Db;

class CustomerModel extends model{

    public static function login( $name, $password ){

        $sql = "select * from sh_customer where name='". $name
            ."' and password='". $password ."' ";
//        $result = self::$db->query( $sql );
//        return !empty($result->row)?$result->row:false;

        $result = Db::query( $sql )[0];

        return !empty($result) ? $result : false;

    }

    public static function removeCustomerXcx( $openid ){

        $sql = 'delete from sh_customer_xcx where open_id="' . $openid . '" ';
        // pdo_query( $sql );
        Db::execute( $sql );
    }


    public static function getCustomerById( $id ){
        $condition = [
            'id'=>$id
        ];
        $result = sm_pdo_get('customer', $condition );
        return !empty($result) ? $result : false;
    }

    // 获取下级用户
    public static function getCustomersByReferee( $referee_id ){
        $condition = [
            'referee'=>$referee_id
        ];
        $result = sm_pdo_getall('customer', $condition );
        return !empty($result) ? $result : false;
    }

    public static function getCustomer( $openid ){

        $sql = "select * from sh_customer  where open_id='" . $openid . "'";
        return pdo_fetch( $sql );
    }

    public static function setCustomerXcx( $openid, $phone ){

        $sql = 'insert into sh_customer_xcx set open_id="' . $openid
            . '", telephone="' . $phone . '"';
        // return pdo_query( $sql );
        return Db::execute( $sql );

    }

    public static function registerByXcx( $openid, $telephone, $referee = 0, $userInfo = [] ){

        global $_W;
//        customerModel::removeCustomerXcx( $openid );
//        self::setCustomerXcx( $openid, $telephone );

        $customer = self::getCustomerByPhone( $telephone );


        // todo 用户添加到微擎自身数据表中
        $w7_uid = 0;
        // if( !empty($userInfo) ){
        //     $w7_uid = self::customer2Member( $userInfo );
        // }


        if( empty( $customer ) ){
            $date = Date("Y-m-d H:i:s");
            $nickname = !empty( $userInfo['nickName'] ) ?$userInfo['nickName']:'';
            $headUrl = !empty( $userInfo['avatarUrl'] ) ?$userInfo['avatarUrl']:'';
            $info = !empty( $userInfo ) ? json_encode( $userInfo ) :'';


            $sql = "insert into sh_customer set "
                . " uniacid='" . $_W['uniacid']
                . "', referee='" . $referee
                . "', open_id='" . $openid
                . "', w7_uid='" . $w7_uid
                . "', telephone='" . $telephone
                . "', password='" . substr($telephone,-6)
                . "', `name`='" . $nickname
                . "', headUrl='" . $headUrl
                . "', info='" . $info
                . "', create_time='" . $date
                . "', customer_group_id='1'"
                . ", remark=''"
                . " , status=1 ";

            pdo_query( $sql );
            // Db::execute( $sql );

            // $customer_id = pdo_insertid();
            $customer_id = Db::name("sh_customer")->getLastInsID();

            // todo 添加用户链
            if( $referee ){
                self::setCustomerChain( $referee, $customer_id );
            }


            return $customer_id;
        }else{

            if( !empty( $userInfo ) ){
                self::update2( $telephone, $userInfo );
            }


            return $customer['id'];
        }

    }

    /**
     * @param $userInfo
     * @param int $referee
     * @return mixed
     */
    public static function registerByApp( $userInfo, $referee = 0  ){

        global $_W;

        $customer = self::getCustomer( $userInfo['openId'] );


        // todo 用户添加到微擎自身数据表中
        $w7_uid = 0;
        if( !empty($userInfo) ){
            $w7_uid = self::customer2Member( $userInfo );
        }


        if( empty( $customer ) ){
            $date = Date("Y-m-d H:i:s");
            $nickname = !empty( $userInfo['nickName'] ) ?$userInfo['nickName']:'';
            $headUrl = !empty( $userInfo['avatarUrl'] ) ?$userInfo['avatarUrl']:'';
            $info = !empty( $userInfo ) ? json_encode( $userInfo ) :'';


            $sql = "insert into sh_customer set "
                . " uniacid='" . $_W['uniacid']
                . "', referee='" . $referee
                . "', open_id='" . $userInfo['openid']
                . "', w7_uid='" . $w7_uid
//                . "', telephone='" . $telephone
                . "', `name`='" . $nickname
                . "', headUrl='" . $headUrl
                . "', info='" . $info
                . "', create_time='" . $date
                . "', customer_group_id='1'"
                . " , status=1 ";

            // pdo_query( $sql );
            Db::execute( $sql );

            // $customer_id = pdo_insertid();
            $customer_id = Db::name("sh_customer")->getLastInsID();

            // todo 添加用户链
            if( $referee ){
                self::setCustomerChain( $referee, $customer_id );
            }


            return $customer_id;
        }else{

            if( !empty( $userInfo ) ){
                self::update2( $telephone, $userInfo );
            }


            return $customer['id'];
        }

    }

    public static function update2( $telephone, $data ){

        $nickname = !empty( $data['nickName'] ) ?$data['nickName']:'';
        $headUrl = !empty( $data['avatarUrl'] ) ?$data['avatarUrl']:'';
        $info = is_array( $data ) ? json_encode( $data ) : '';

        $sql = " update sh_customer set "
            . " `name`='" . $nickname
            . "', headUrl='" . $headUrl
            . "', info='" . $info
            . "' where telephone='" . $telephone . "'";

        // return pdo_query( $sql );
        return Db::execute( $sql );
    }

    public static function getCustomerByPhone( $telephone ){

        global $_W;
        $sql = 'select * from sh_customer where '
            . ' telephone="' . $telephone . '"'
            . ' and uniacid="' . $_W['uniacid'] . '"'
        ;

        return pdo_fetch( $sql );
        // return Db::query( $sql )[0];

    }

    public static function getCustomerQrcode( $customer_id ){

        global $_W;
        $sql = 'select * from sh_customer_qrcode where '
            . ' customer_id="' . $customer_id . '"'
            . ' and uniacid= ' . $_W['uniacid']
        ;

        return pdo_fetch( $sql );

    }

    public static function setCustomerQrcode( $data ){
        global $_W;

        $sql = 'insert into sh_customer_qrcode set '
            . ' customer_id="' . $data['customer_id'] . '",'
            . ' scene="' . $data['scene'] . '",'
            . ' qrcode_path="' . $data['qrcode_path'] . '",'
            . ' uniacid= ' . $_W['uniacid']
        ;

        // pdo_query( $sql );
        Db::execute( $sql );

        // return pdo_insertid();
        return Db::name("sh_customer_qrcode")->getLastInsID();
    }

    public static function setCustomerChain(){

    }

    // 用户数据添加到系统自身的数据表中
    public static function customer2Member(  $wechat_info ){

        global  $_W;
        $openid = !empty($wechat_info['openid'])?$wechat_info['openid']:$_W['openid'];
        $params = [
            'openid'=>$openid
        ];
        $fan = pdo_get('mc_mapping_fans', $params );

        if( empty($fan) ){

//            $wechat_info = json_decode( $customer['info'], true);
            $record = array(
                'openid' => $openid,
                'uid' => 0,
                'acid' => $_W['uniacid'],
                'uniacid' => $_W['uniacid'],
                // 'salt' => random(8),
                'salt' => rand(10000000,99999999),
                'updatetime' => 'TIMESTAMP',
                'nickname' => $wechat_info['nickName'],
                'follow' => 0,
                'followtime' => 0,
                'unfollowtime' => 0,
                // 'tag' => base64_encode(iserializer('')),
                'tag' => '',
                'unionid' => isset($wechat_info['unionId'])?$wechat_info['unionId']:'',
                'user_from' => isset($wechat_info['user_from'])?$wechat_info['user_from']:1, // 1: 小程序，0：公众号
            );

            // $default_groupid = table('mc_groups')
            //     ->where(array(
            //         'uniacid' => $_W['uniacid'],
            //         'isdefault' => 1
            //     ))
            //     ->getcolumn('groupid');
            $data = array(
                'uniacid' => $_W['uniacid'],
                // 'email' => $openid.'@we7.cc',
                'email' => $openid.'@openid.com',
                // 'salt' => random(8),
                'salt' => rand(10000000,99999999),
                // 'groupid' => $default_groupid,
                'groupid' => 0,
                'createtime' => 'TIMESTAMP',
                'password' => md5('xcx' . $record['salt'] . $_W['config']['setting']['authkey']),
                'nickname' => $wechat_info['nickName'],
                'avatar' => $wechat_info['headUrl'],
                'gender' => isset($wechat_info['gender'])?$wechat_info['gender']:1,
                'nationality' => isset($wechat_info['country'])?$wechat_info['country']:'',
                'resideprovince' => isset($wechat_info['province'])?$wechat_info['province']:'',
                'residecity' => isset($wechat_info['city'])?$wechat_info['city']:'',
                'user_from' => isset($wechat_info['user_from'])?$wechat_info['user_from']:1, // 1: 小程序，0：公众号
            );
            table('mc_members')
                ->fill($data)
                ->save();
            // $uid = pdo_insertid();
            $uid = Db::name("mc_members")->getLastInsID();;
            
            $record['uid'] = $uid;
            $_SESSION['uid'] = $uid;
            table('mc_mapping_fans')->fill($record)->save();

            return $uid;
        }

        return $fan['uid'];
    }

    public static function group(){
        global $_W;

        $id = $_W['member']['groupid']?$_W['member']['groupid']:0;
        if( !empty( $id ) ){
            return pdo_get('mc_groups', ['groupid'=>$id]);
        }

        return null;
    }

    // 独立版暂时用不到，先注释
    public static function credit(){

        global $_W;
        //  获取积分的名称 table:uni_settings
        //  获取积分 table:mc_members

        $credit_val = mc_credit_fetch( $_W['member']['uid']);
        $creditnames = $_W['account']['setting']['creditnames'];

        foreach( $creditnames as $key => &$item ){
            $item['value'] = $credit_val[$key];
        }
        return $creditnames;
    }

    public static function getLowerOrderTotal( $customer_id ){

        $sql = 'select sum(o.total) as total from sh_order o '
            . ' inner join sh_customer c on o.customer_id=c.id '
            . ' where c.referee= ' . $customer_id;
        // return pdo_fetchcolumn( $sql );
        $res = Db::query( $sql );
        return $res ? $res[0]['total'] : 0;
    }

}